﻿function Widget_Email(obj)
{
   this.initializeBase(obj);
}
Widget_Email.prototype = new WidgetInstance;

Widget_Email.prototype.Refresh = function()
{
   this.DisplayDiv(3);
   WriteHistory("Widget_Email.prototype.Refresh #" + this.id);
   //Query proxyasync for the rss feed
   
   //Proxy.GetRss(this.FeedURL,parseInt(this.FeedCount),10,Function.createDelegate( this, this.onContentLoad ));
   grabContent("/widgets/mail/email/grab.aspx?action=&id=" + this.id, Function.createDelegate(this, this.onContentLoad));
}

Widget_Email.prototype.DisplayDiv = function(id)
{
   var Ajax = $('wdiv_Ajax' + this.id);
   Ajax.style.display = "none";
   var Grid = $('wdiv_Grid' + this.id);
   Grid.style.display = "none";
   var Msg =$("wdiv_Msg" + this.id);
   Msg.style.display = "none";
   var Reply =$("wdiv_Reply" + this.id);
   Reply.style.display = "none";
   
   switch(id)
   {
      case 0:
         Grid.style.display = "block";
         break;
      case 1:
         Msg.style.display = "block";
         break;
      case 2:
         Reply.style.display = "block";
         break;
      case 3:
         Ajax.style.display = "block";
         break;
   }
}
Widget_Email.prototype.onContentLoad = function(content)
{
   WriteHistory("Widget_Email.prototype.onContentLoad #" + this.id);
   var div = $get('wdiv_Grid' + this.id);   
   
   if (content.length > 0)
   {
      var xotree = new XML.ObjTree();
      var xmlDoc = xotree.parseXML(content);
      var status = xmlDoc.result.Status;
      this.Emails = xmlDoc.result.Emails;

      if (status == "OK")
      {
         removeChildNodes(div);
         var ClickScripts = new Array();         
         
         if (this.Emails)
         {
            for(var EmailID in this.Emails)
            {
               var Email = this.Emails[EmailID];

               var eDiv = document.createElement("div");
               eDiv.id = "d" + this.id + "x" + Email.UID;         
               eDiv.className = "WMessage";
               eDiv.title = "Click to read email";
               eDiv.onmouseover = function() {this.className='WMessage_Over';};
               eDiv.onmouseout = function() {this.className='WMessage';};
               ClickScripts.push("$('" + eDiv.id + "').onclick = function() {$WI(" + this.id + ").ShowMessage(" + Email.UID + ");}");
               
               
               var td_Date = document.createElement("td");
               td_Date.innerHTML = Email.Date;
               
               var td_From = document.createElement("td");
               td_From.innerHTML = Email.From + "<br />" + Email.Subject;
               
               eDiv.innerHTML = "<table border='0' width='95%'><tbody><tr><td width='75%'>" + 
                                 td_From.innerHTML + "</td><td width='25%'>" +
                                 td_Date.innerHTML + "</td></tr></tbody></table>";
               div.appendChild(eDiv);
            }
            
            while(ClickScripts.length > 0)
            {
               installScript(ClickScripts.pop());
            }
         }
         else
         {
            div.innerHTML = "<i>You have no emails.</i>";
         }
         
         div.innerHTML = "<a href='javascript:void(0)' onclick=\"$WI(" + this.id + ").SendMessage(0);\">Compose Email</a><hr>" + div.innerHTML;
      }
      else
      {
         div.innerHTML = status;
      }
   }
   else
   {
      div.innerHTML = "Please configure your client";
   }
   this.DisplayDiv(0);   
}

Widget_Email.prototype.ShowMessage = function(UID)
{
   WriteHistory("Widget_Email.prototype.ShowMessage:" + UID);
   for(var EmailID in this.Emails)
   {
      var Email = this.Emails[EmailID];
      WriteHistory(Email.UID + ":" + UID);
      if (Email.UID == UID)
      {
         this.DisplayDiv(1);
         $("tr_MsgFrom" + this.id).innerHTML = Email.From;
         $("tr_MsgSubj" + this.id).innerHTML = Email.Subject;
         $("tr_MsgBody" + this.id).innerHTML = Email.Body;
         installScript("$('btn_MsgReply" + this.id + "').onclick = function() {$WI(" + this.id + ").SendMessage(" + Email.UID + ");}");
      }
   }
}

Widget_Email.prototype.SendMessage = function(UID)
{
   WriteHistory("Widget_Email.prototype.SendMessage:" + UID);
   this.DisplayDiv(2);
   
   var wdiv_ReplyTo = $("wdiv_ReplyTo" + this.id);
   var wdiv_ReplySubject = $("wdiv_ReplySubject" + this.id);
   var wdiv_ReplyBody = $("wdiv_ReplyBody" + this.id);
   
   wdiv_ReplyTo.value = "";
   wdiv_ReplySubject.value = "";
   wdiv_ReplyTo.value = "";
   
   if (UID > 0)
   {
      for(var EmailID in this.Emails)
      {
         var Email = this.Emails[EmailID];
         WriteHistory(Email.UID + ":" + UID);
         if (Email.UID == UID)
         {
            wdiv_ReplyTo.value = Email.EmailFrom;
            wdiv_ReplySubject.value = "RE: " + Email.Subject;
            wdiv_ReplyBody.value = "---------------------\n" + Email.Text;
            installScript("$('btn_MsgReply" + this.id + "').onclick = function() {$WI(" + this.id + ").SendMessage(" + Email.UID + ");}");
         }
      }
   }
}

Widget_Email.prototype.Send = function()
{
   var request = new Sys.Net.WebRequest();
   request.set_httpVerb("POST");
   request.set_url("/widgets/mail/email/send.aspx");

   var wdiv_ReplyTo = $("wdiv_ReplyTo" + this.id);
   var wdiv_ReplySubject = $("wdiv_ReplySubject" + this.id);
   var wdiv_ReplyBody = $("wdiv_ReplyBody" + this.id);
   
   var body = "id=" + this.id + "&To=" + wdiv_ReplyTo.value.escapeHTML() + "&Subject=" + wdiv_ReplySubject.value.escapeHTML() + "&Body=" + wdiv_ReplyBody.value.escapeHTML();
   request.set_body(body);
   request.get_headers()["Content-Length"] = body.length
   request.add_completed(Function.createDelegate(this, this.SendComplete));
 
   var executor = new Sys.Net.XMLHttpExecutor();
   request.set_executor(executor); 
   executor.executeRequest();
   this.DisplayDiv(0);
   this.Status.innerHTML = "Sending Email..";
   this.Status.title = "To: " + wdiv_ReplyTo.value + "\nSubject: " + wdiv_ReplySubject.value;
   
}

Widget_Email.prototype.SendComplete = function(executor)
{
   if (executor.get_responseAvailable()) 
   {
      var content = executor.get_responseData();
      this.Status.innerHTML = content;
      WriteHistory(content);
   }
}

Widget_Email.prototype.Load = function()
{
   this.Menu_Edit = new Array();
   this.Menu_Edit.push("m" + this.id + "_edit");
   this.Widget.InstanceLoad();

   this.WidgetDiv_BodySettings = $get('wdivbs' + this.id);
   this.WidgetDiv_BodyContent = document.getElementById("wdivbc" + this.Widget.id);
   this.WidgetDiv_Command_Edit = document.getElementById("wdivc_edit" + this.Widget.id);
   
   this.Settings_Tab = $get("wt_Settings" + this.id);
   this.Settings_Div = $get("ws_Settings" + this.id);
      
   this.Preferences_Tab = $get("wt_Preferences" + this.id);
   this.Preferences_Div = $get("ws_Preferences" + this.id);
   this.Preferences_Title = $get("ws_Title" + this.id);
   this.Preferences_Height = $get("ws_Height" + this.id);
   
   this.Settings_ws_Mail = $get("ws_Mail" + this.id);
   this.Settings_ws_IMAP = $get("ws_IMAP" + this.id);
   this.Settings_ws_SMTP = $get("ws_SMTP" + this.id);
   this.Settings_ws_UserID = $get("ws_UserID" + this.id);
   this.Settings_ws_EmailFrom = $get("ws_EmailFrom" + this.id);
   this.Settings_ws_Password = $get("ws_Password" + this.id);
   this.Settings_ws_IMAP_Secure = $get("ws_IMAP_Secure" + this.id);
   this.Settings_ws_SMTP_Secure = $get("ws_SMTP_Secure" + this.id);
   this.Settings_ws_SMTP_RequireLogin = $get("ws_SMTP_RequireLogin" + this.id);
   
   this.Status = $("lbl_Status" + this.id);
   
   if (this.Widget.obj.State)
   {   
      var xotree = new XML.ObjTree();
      var xmlDoc = xotree.parseXML(this.Widget.obj.State);
      
      if (xmlDoc.state.UserID)
         this.Settings_ws_UserID.value = xmlDoc.state.UserID;
      else
         this.Settings_ws_UserID.value = "";
      
      if (xmlDoc.state.EmailFrom)
         this.Settings_ws_EmailFrom.value = xmlDoc.state.EmailFrom;
      else
         this.Settings_ws_EmailFrom.value = "";
         
      this.Settings_ws_Mail.value = xmlDoc.state.Mail;
      this.Client_ChangeMailServer();
      this.Settings_ws_IMAP.value = xmlDoc.state.IMAP;
      this.Settings_ws_SMTP.value = xmlDoc.state.SMTP;
      this.Settings_ws_IMAP_Secure.checked = xmlDoc.state.IMAP_Secure == 1;
      this.Settings_ws_SMTP_Secure.checked = xmlDoc.state.SMTP_Secure == 1;
      this.Settings_ws_SMTP_RequireLogin.checked = xmlDoc.state.SMTP_Login == 1;
   }
   
   
   //Hide them both
   this.Settings_Div.style.display="none";
   this.Preferences_Div.style.display="none";

   var theState = this.Widget.obj.State;
   this.FeedCount = parseInt(theState.substring(0, theState.indexOf(",")));
   
   if (!this.FeedCount || isNaN(this.FeedCount))
   {
      this.FeedCount = 0;
   }
   this.FeedURL = theState.substring(theState.indexOf(",")+1);
   
   this.Refresh();
   
   this.Widget.InstanceLoadComplete();
   
   this.inSettings = true;
   this.ShowSettings();
}

Widget_Email.prototype.ShowSettings = function()
{
   this.Settings_Tab.className="WSettings_Tab_S WSettings_S";
   this.Settings_Div.style.display='block';

   this.Preferences_Tab.className="WSettings_Tab";
   this.Preferences_Div.style.display='none';
   this.inSettings = true;
   if (this.inEditMode)
      this.Settings_ws_UserID.focus();
}

Widget_Email.prototype.ShowPreferences = function()
{
   this.Settings_Tab.className="WSettings_Tab";
   this.Settings_Div.style.display='none';

   this.Preferences_Tab.className="WSettings_Tab_S WSettings_S";
   this.Preferences_Div.style.display='block';
   
   this.Preferences_Title.value = this.Widget.obj.Title;
   this.Preferences_Height.value = this.Widget.obj.Height;
   
   if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_EditTitle))
   {
      this.Preferences_Title.disabled = false;
      if (this.inEditMode)
         this.Preferences_Title.focus();
   }
   else
   {
      this.Preferences_Title.disabled = true;
      if (this.inEditMode)
         this.Preferences_Height.focus();
   }
   
   this.inSettings = false;
}

Widget_Email.prototype.SaveEnc = function()
{
   if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_Edit))
   {
      if (RsaSecurityHelper.isValid())
      {
         var UserID = this.Settings_ws_UserID.value;
         var Password = this.Settings_ws_Password.value;
         var EmailFrom = this.Settings_ws_EmailFrom.value;
         var IMAP = this.Settings_ws_IMAP.value;
         var SMTP = this.Settings_ws_SMTP.value;
         var IMAP_Secure = (this.Settings_ws_IMAP_Secure.checked ? 1 : 0);
         var SMTP_Secure = (this.Settings_ws_SMTP_Secure.checked ? 1 : 0);
         var SMTP_Login = (this.Settings_ws_SMTP_RequireLogin.checked ? 1 : 0);
         var SavePassword = $("ws_PasswordSave" + this.id).checked;
         if (UserID.length > 0 && Password.length > 0 && IMAP.length > 0 && EmailFrom.length > 0 && SMTP.length > 0)
         {
            var Dict = new Object();
            Dict.EmailFrom = EmailFrom;
            Dict.UserID = UserID;
            Dict.IMAP = IMAP;
            Dict.SMTP = SMTP;
            Dict.IMAP_Secure = IMAP_Secure;
            Dict.SMTP_Secure = SMTP_Secure;
            Dict.SMTP_Login = SMTP_Login;
            Dict.Mail = this.Settings_ws_Mail.value;
            Dict.Enc_Password = RsaSecurityHelper.encrypt(Password);
            
            JSON.Widget_UpdateProperties(this.Widget.Tab.id, this.id, Dict);
            this.Refresh();
         }
         else
         {
            alert("Please fill in all required fields");
         }
      }
      else
      {
         setTimeout(Function.createDelegate(this,this.SaveEnc),1000);
      }
   }
}

//saves the setting
Widget_Email.prototype.Save = function()
{
   if (this.inSettings)
   {
      if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_Edit))
      {
         var UserID = this.Settings_ws_UserID.value;
         var Password = this.Settings_ws_Password.value;
         var EmailFrom = this.Settings_ws_EmailFrom.value;
         var IMAP = this.Settings_ws_IMAP.value;
         var SMTP = this.Settings_ws_SMTP.value;
         var IMAP_Secure = (this.Settings_ws_IMAP_Secure.checked ? 1 : 0);
         var SMTP_Secure = (this.Settings_ws_SMTP_Secure.checked ? 1 : 0);
         var SMTP_Login = (this.Settings_ws_SMTP_RequireLogin.checked ? 1 : 0);
         if (UserID.length > 0 && Password.length > 0 && IMAP.length > 0 && EmailFrom.length > 0 && SMTP.length > 0)
         {
            RsaSecurityHelper.getSessionKey();
            setTimeout(Function.createDelegate(this,this.SaveEnc),1000);
            //setElementToAjaxLoading(this.WidgetDiv_BodyContent);
         }
         else
         {
            alert("Please ensure that you have entered all compulsory fields");
            return;
         }
      }         
   }
   else
   {
      var theHeight= parseInt(this.Preferences_Height.value);
      if (parseInt(this.Widget.obj.Height) != theHeight)
      {
         //Save only if changes
         this.Widget.obj.Height = theHeight;      

          if (this.ResizeHeightComplete)
            this.ResizeHeightComplete(theHeight);
          this.SaveHeight(theHeight);
      }

     if (myTabs.hasRequiredTabPermission(this.Tab, TabAccessLevel.Widget_EditTitle))
     {
        if (this.Widget.obj.Title != this.Preferences_Title.value)
        {
           this.Widget.obj.Title = this.WidgetDiv_Header_Lbl.innerHTML = this.WidgetDiv_Header_Input.value = this.Preferences_Title.value;         
           JSON.Widget_UpdateProperty(this.Widget.Tab.id, this.id, 'title', this.Widget.obj.Title);
        }
     }      
   }
   this.Edit();
}

Widget_Email.prototype.Client_ChangeMailServer = function()
{
   switch(this.Settings_ws_Mail.value)
   {
      case "nus":
         this.Settings_ws_IMAP.value = "imap.nus.edu.sg"
         this.Settings_ws_SMTP.value = "smtp.nus.edu.sg"
         this.Settings_ws_IMAP_Secure.checked = true;
         this.Settings_ws_SMTP_Secure.checked = true;
         this.Settings_ws_SMTP_RequireLogin.checked = true;

         this.Settings_ws_IMAP.disabled = true;
         this.Settings_ws_SMTP.disabled = true;
         this.Settings_ws_IMAP_Secure.disabled = true;
         this.Settings_ws_SMTP_Secure.disabled = true;
         this.Settings_ws_SMTP_RequireLogin.disabled = true;
         break;
      case "gmail":
         this.Settings_ws_IMAP.value = "imap.gmail.com"
         this.Settings_ws_SMTP.value = "smtp.gmail.com:587"
         this.Settings_ws_IMAP_Secure.checked = true;
         this.Settings_ws_SMTP_Secure.checked = true;
         this.Settings_ws_SMTP_RequireLogin.checked = true;

         this.Settings_ws_IMAP.disabled = true;
         this.Settings_ws_SMTP.disabled = true;
         this.Settings_ws_IMAP_Secure.disabled = true;
         this.Settings_ws_SMTP_Secure.disabled = true;
         this.Settings_ws_SMTP_RequireLogin.disabled = true;
         break;
      case "o":
         this.Settings_ws_IMAP.value = ""
         this.Settings_ws_SMTP.value = ""
         this.Settings_ws_IMAP_Secure.checked = false;
         this.Settings_ws_SMTP_Secure.checked = false;
         this.Settings_ws_SMTP_RequireLogin.checked = true;      
         
         this.Settings_ws_IMAP.disabled = false;
         this.Settings_ws_SMTP.disabled = false;
         this.Settings_ws_IMAP_Secure.disabled = false;
         this.Settings_ws_SMTP_Secure.disabled = false;
         this.Settings_ws_SMTP_RequireLogin.disabled = false;         
         break;
   }
}